package com.example.demo.service.system.impl;

import com.example.demo.entity.CollectionName;
import com.example.demo.entity.Result;
import com.example.demo.service.file.FileService;
import com.example.demo.service.system.SlideShowService;
import com.example.demo.utils.DateUtil;
import com.example.demo.utils.OssUtil;
import com.mongodb.client.result.UpdateResult;
import org.bson.types.ObjectId;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.GroupOperation;
import org.springframework.data.mongodb.core.aggregation.MatchOperation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.*;

/**
 * @description:
 * @author: cj
 * @create: 12-01-10 12:02:39
 */
@Service
public class SlideShowServiceImpl implements SlideShowService {
    @Resource
    OssUtil ossUtil;
    @Resource
    FileService fileService;
    @Resource
    MongoTemplate mongoTemplate;

    /**
     * 添加轮播图
     */
    @Override
    public Result add(MultipartFile file) throws IOException {
        //上传到阿里云 oos
//        Map<String, Object> uploadFileMap = ossUtil.uploadFile( file );
        Map<String, Object> uploadFileMap = fileService.uploadFile ( file );
        Map<String, Object> map = new HashMap<>( 9 );
        map.putAll( uploadFileMap );
        map.put( "createTime", DateUtil.dateToString( new Date() ) );
        map.put( "state", "1" );
        Map<String, Object> insert = mongoTemplate.insert( map, CollectionName.SYSTEM_SLIDESHOW );
        insert.put( "_id", insert.get( "_id" ).toString() );
        return Result.ok( insert );
    }

    /**
     * 删除轮播图
     *
     * @param list 图片id集合
     */
    @Override
    public Result del(List<String> list) {
        Criteria id = Criteria.where( "_id" ).in( list );
        MatchOperation match = Aggregation.match( id );
        GroupOperation as = Aggregation.group().push( "fileName" ).as( "fileNames" );
        Aggregation aggregation = Aggregation.newAggregation( match, as );
        AggregationResults<Map> aggregate = mongoTemplate.aggregate( aggregation, CollectionName.SYSTEM_SLIDESHOW, Map.class );
        Map aggregateMap = aggregate.getUniqueMappedResult();
        if (aggregateMap == null || aggregateMap.isEmpty()) {
            throw new RuntimeException( "未找到该图片" );
        }
        List<String> fileNames = (List<String>) aggregateMap.get( "fileNames" );
        ossUtil.del( fileNames );
        mongoTemplate.remove( Query.query( id ), CollectionName.SYSTEM_SLIDESHOW );
        return Result.ok( "操作成功" );
    }

    /**
     * 查找轮播图
     *
     * @param page     分页参数
     * @param pageSize 分页参数
     * @return 图片集合
     */
    @Override
    public Result find(Integer page, Integer pageSize) {
        List<Map> mapList = mongoTemplate.find( Query.query( new Criteria() ).skip( (page - 1) * pageSize ).limit( pageSize ),
                Map.class, CollectionName.SYSTEM_SLIDESHOW );
        return Result.ok( mapList );
    }

    /**
     * 修改轮播图
     *
     * @param file 修改的图片
     * @param id   要修改的id
     * @return 修改后的数据
     */
    @Override
    public Result update(MultipartFile file, String id) throws IOException {
        //查找图片 判断是否有效
        if (!ObjectId.isValid( id )) {
            throw new RuntimeException( "id格式错误" );
        } else {
            Map img = mongoTemplate.findById( id, Map.class, CollectionName.SYSTEM_SLIDESHOW );
            if (img == null || img.isEmpty()) {
                throw new RuntimeException( "未找到该图片" );
            } else {
                //存在 就删除
                String fileName = img.get( "fileName" ).toString();
                ossUtil.del( Collections.singletonList( fileName ) );
                //修改为当前的
                Map<String, Object> map = ossUtil.uploadFile( file );
                Update update = new Update();
                update.set( "fileName", map.get( "fileName" ).toString() );
                update.set( "path", map.get( "path" ).toString() );
                mongoTemplate.updateFirst( Query.query( Criteria.where( "_id" ).is( id ) ), update, CollectionName.SYSTEM_SLIDESHOW );
                map.putAll( img );
                return Result.ok( map );
            }

        }
    }

}
